<template>
  <div class="brand-management-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2 class="page-title">品牌管理</h2>
      <el-button type="text" class="return-btn" @click="handleReturn">返回</el-button>
    </div>

    <!-- 操作区域 -->
    <div class="action-area">
      <el-button 
        type="primary" 
        class="add-btn" 
        @click="openAddDialog"
      >
        增加
      </el-button>
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索品牌名称/经理..." 
        style="width: 240px;"
        @keyup.enter="handleSearch"
      />
      <el-button 
        type="primary" 
        class="search-btn"
        @click="handleSearch"
      >
        搜索
      </el-button>
    </div>

    <!-- 品牌列表表格 -->
    <el-table 
      :data="filteredBrandList" 
      border 
      style="width: 100%;"
      :row-key="row => row.id"
      v-loading="tableLoading"
    >
      <el-table-column label="品牌LOGO" width="80">
        <template #default="scope">
          <el-avatar :src="scope.row.logo" class="brand-logo" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="品牌名称" sortable />
      <el-table-column prop="manager" label="品牌经理" sortable />
      <el-table-column prop="company" label="所属公司" />
      <el-table-column prop="contact" label="联系方式" />
      <el-table-column prop="mentor" label="品牌导师" sortable>
        <template #default="scope">
          <el-select v-model="scope.row.mentor" disabled>
            <el-option v-for="item in mentorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="品牌权限" width="120">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.isOpen" 
            :active-value="true" 
            :inactive-value="false" 
            active-text="开放" 
            inactive-text="关闭" 
            active-color="#00b4b4" 
            @change="handleOpenChange(scope.row)"
            :disabled="!scope.row.id"
          />
        </template>
      </el-table-column>
      <el-table-column prop="designatedStore" label="指定开放" />
      <el-table-column prop="discountLevel" label="折扣档位">
        <template #default="scope">
          <el-select v-model="scope.row.discountLevel" disabled>
            <el-option v-for="item in discountLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="singleDiscount" label="单品折扣" />
      <el-table-column prop="setDiscount" label="套盒折扣" />
      <el-table-column prop="intro" label="品牌简介" width="200">
        <template #default="scope">
          <div class="intro-text">{{ scope.row.intro }}</div>
        </template>
      </el-table-column>
      <el-table-column label="库存数据" width="100">
        <template #default="scope">
          <el-button 
            type="primary" 
            
            class="inventory-btn"
            @click="viewInventory(scope.row)"
          >
            {{ scope.row.inventory }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button 
            type="warning" 
         
            @click="openEditDialog(scope.row)"
            class="edit-btn"
          >
            修改
          </el-button>
          <el-button 
            type="danger" 
             
            @click="handleDelete(scope.row)"
            class="delete-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态提示 -->
    <div v-if="filteredBrandList.length === 0 && !tableLoading" class="empty-state">
      <el-empty description="暂无品牌数据" />
    </div>

    <!-- 分页区域 -->
    <div v-if="filteredBrandList.length > 0" class="pagination-area">
      <span class="total-info">共 {{ filteredBrandList.length }} 条 共 {{ totalPages }} 页</span>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="filteredBrandList.length"
      />
      <el-select 
        v-model="pageSize" 
        @change="handleSizeChange" 
        placeholder="条数/页" 
        style="width: 100px; margin-left: 10px;"
      >
        <el-option label="10条/页" value="10" />
        <el-option label="20条/页" value="20" />
        <el-option label="30条/页" value="30" />
      </el-select>
      <span>跳至</span>
      <el-input 
        v-model="jumpPage" 
        type="number" 
        style="width: 50px; margin: 0 5px;"
        @keyup.enter="handleJump"
        :min="1"
        :max="totalPages"
        :disabled="totalPages < 1"
      />页
      <el-button 
        type="primary" 
        
       
        @click="handleJump"
        :disabled="totalPages < 1"
      >
        确定
      </el-button>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑品牌' : '新增品牌'" 
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌经理" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入品牌经理" />
        </el-form-item>
        <el-form-item label="所属公司" prop="company">
          <el-input v-model="form.company" placeholder="请输入所属公司" />
        </el-form-item>
        <el-form-item label="手机号码" prop="contact">
          <el-input 
            v-model="form.contact" 
            placeholder="请输入手机号码" 
            :maxlength="11"
            @input="handleContactInput"
          />
        </el-form-item>
        <el-form-item label="品牌导师" prop="mentor">
          <el-select v-model="form.mentor" placeholder="请选择品牌导师" clearable>
            <el-option v-for="item in mentorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌权限" prop="isOpen">
          <el-switch 
            v-model="form.isOpen" 
            :active-value="true" 
            :inactive-value="false" 
            active-text="开放" 
            inactive-text="关闭" 
            active-color="#00b4b4" 
          />
        </el-form-item>
        <el-form-item label="指定开放" prop="designatedStore">
          <el-select v-model="form.designatedStore" placeholder="请选择指定门店" clearable>
            <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣档位" prop="discountLevel">
          <el-select v-model="form.discountLevel" placeholder="请选择折扣档位" clearable>
            <el-option v-for="item in discountLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单品折扣" prop="singleDiscount">
          <el-input v-model="form.singleDiscount" placeholder="请输入单品折扣" />
        </el-form-item>
        <el-form-item label="套盒折扣" prop="setDiscount">
          <el-input v-model="form.setDiscount" placeholder="请输入套盒折扣" />
        </el-form-item>
        <el-form-item label="品牌简介" prop="intro">
          <el-input v-model="form.intro" placeholder="请输入品牌简介" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="LOGO上传" prop="logo">
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleLogoUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <el-button   type="primary">选择文件</el-button>
            <div class="upload-info" v-if="form.logoName">已选择文件: {{ form.logoName }}</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="库存数据" prop="inventory">
          <el-input 
            v-model="form.inventory" 
            placeholder="请输入库存数据" 
            type="number"
            min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitLoading"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, ElEmpty, ElDivider, ElAvatar, ElUpload } from 'element-plus';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 验证品牌名称是否重复（必须在formRules前定义）
const checkNameDuplicate = (rule, value, callback) => {
  if (!value) return callback();
  
  const isDuplicate = brandList.value.some(item => 
    item.name.trim().toLowerCase() === value.trim().toLowerCase() && item.id !== form.id
  );
  
  if (isDuplicate) {
    callback(new Error('该品牌名称已存在'));
  } else {
    callback();
  }
};

// 状态管理
const brandList = ref([]); // 原始数据
const filteredBrandList = ref([]); // 筛选后的数据
const searchKeyword = ref('');
const tableLoading = ref(false);
const submitLoading = ref(false);

// 表单数据
const form = reactive({
  id: '',
  name: '',
  manager: '',
  company: '21世纪企业',
  contact: '',
  mentor: '',
  isOpen: false,
  designatedStore: '',
  discountLevel: '',
  singleDiscount: '',
  setDiscount: '',
  intro: '',
  logo: '',
  logoName: '',
  inventory: 0
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 20, message: '品牌名称长度在 2 到 20 个字符', trigger: 'blur' },
    { validator: checkNameDuplicate, trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '请输入品牌经理', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入所属公司', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  mentor: [
    { required: true, message: '请选择品牌导师', trigger: 'change' }
  ],
  designatedStore: [
    { required: true, message: '请选择指定门店', trigger: 'change' }
  ],
  discountLevel: [
    { required: true, message: '请选择折扣档位', trigger: 'change' }
  ],
  singleDiscount: [
    { required: true, message: '请输入单品折扣', trigger: 'blur' }
  ],
  setDiscount: [
    { required: true, message: '请输入套盒折扣', trigger: 'blur' }
  ],
  inventory: [
    { required: true, message: '请输入库存数据', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ]
};

// 对话框控制
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const jumpPage = ref('');
const totalPages = computed(() => {
  return Math.ceil(filteredBrandList.value.length / pageSize.value) || 1;
});

// 下拉选项数据
const mentorOptions = ref([
  { label: '请选择导师', value: '' },
  { label: '李燕平', value: '李燕平' },
  { label: '张晓明', value: '张晓明' },
  { label: '王建国', value: '王建国' },
  { label: '刘静', value: '刘静' }
]);

const storeOptions = ref([
  { label: '请选择指定门店', value: '' },
  { label: '门店A', value: '门店A' },
  { label: '门店B', value: '门店B' },
  { label: '门店C', value: '门店C' },
  { label: '门店D', value: '门店D' }
]);

const discountLevelOptions = ref([
  { label: '请选择折扣档次', value: '' },
  { label: 'A档', value: 'A档' },
  { label: 'B档', value: 'B档' },
  { label: 'C档', value: 'C档' }
]);

// 初始化数据
const initData = async () => {
  try {
    tableLoading.value = true;
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 示例数据
    brandList.value = [
      {
        id: '1',
        name: '测试品牌',
        manager: '李燕平',
        company: '21世纪企业',
        contact: '18932839210',
        mentor: '李燕平',
        isOpen: false,
        designatedStore: '门店A',
        discountLevel: 'A档',
        singleDiscount: '9折',
        setDiscount: '8.5折',
        intro: '这是一个测试品牌的简介内容，用于展示品牌相关信息',
        logo: 'https://via.placeholder.com/100',
        logoName: 'logo.png',
        inventory: 1000
      },
      {
        id: '2',
        name: '高端品牌',
        manager: '张晓明',
        company: '21世纪企业',
        contact: '13845678901',
        mentor: '张晓明',
        isOpen: true,
        designatedStore: '门店B',
        discountLevel: 'B档',
        singleDiscount: '8折',
        setDiscount: '7.5折',
        intro: '高端品牌专注于提供高品质产品和服务',
        logo: 'https://via.placeholder.com/100',
        logoName: 'high_end_logo.png',
        inventory: 500
      }
    ];
    
    filteredBrandList.value = [...brandList.value];
  } catch (error) {
    ElMessage.error('数据加载失败');
    console.error(error);
  } finally {
    tableLoading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  if (!keyword) {
    filteredBrandList.value = [...brandList.value];
  } else {
    filteredBrandList.value = brandList.value.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      item.manager.toLowerCase().includes(keyword) ||
      item.mentor.toLowerCase().includes(keyword)
    );
  }
  // 重置页码
  currentPage.value = 1;
  jumpPage.value = 1;
};

// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false;
  // 重置表单
  Object.assign(form, {
    id: '',
    name: '',
    manager: '',
    company: '21世纪企业',
    contact: '',
    mentor: '',
    isOpen: false,
    designatedStore: '',
    discountLevel: '',
    singleDiscount: '',
    setDiscount: '',
    intro: '',
    logo: '',
    logoName: '',
    inventory: 0
  });
  
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
  });
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  isEdit.value = true;
  // 深拷贝数据
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
  dialogVisible.value = true;
};

// 提交表单（新增/编辑）
const submitForm = async () => {
  try {
    // 表单验证
    await formRef.value.validate();
    submitLoading.value = true;
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500));
    
    if (isEdit.value) {
      // 编辑操作
      const index = brandList.value.findIndex(item => item.id === form.id);
      if (index !== -1) {
        brandList.value.splice(index, 1, { ...form });
        ElMessage.success('品牌编辑成功');
      }
    } else {
      // 新增操作
      const newBrand = {
        ...form,
        id: Date.now().toString(), // 生成唯一ID
      };
      brandList.value.unshift(newBrand); // 添加到列表头部
      ElMessage.success('品牌新增成功');
    }
    
    // 刷新列表
    handleSearch();
    dialogVisible.value = false;
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('操作失败，请重试');
      console.error(error);
    }
  } finally {
    submitLoading.value = false;
  }
};

// 处理联系方式输入（过滤非数字）
const handleContactInput = (value) => {
  form.contact = value.replace(/[^\d]/g, '');
};

// 对话框关闭时清除验证
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 品牌权限状态变更
const handleOpenChange = async (row) => {
  try {
    const originalState = row.isOpen;
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 300));
    ElMessage.success(`品牌${row.isOpen ? '已开放' : '已关闭'}`);
  } catch (error) {
    // 失败时回滚状态
    row.isOpen = !row.isOpen;
    ElMessage.error('状态更新失败');
    console.error(error);
  }
};

// 删除品牌
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除品牌"${row.name}"吗？删除后数据不可恢复`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 执行删除
    const index = brandList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      brandList.value.splice(index, 1);
      handleSearch(); // 刷新列表
      ElMessage.success('品牌删除成功');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }
};

// 查看库存
const viewInventory = (row) => {
  ElMessage.info(`查看${row.name}的库存详情: ${row.inventory}件`);
  // 实际项目中可跳转到库存详情页
  // router.push(`/inventory/detail?brandId=${row.id}`);
};

// 处理LOGO上传
const handleLogoUpload = (file) => {
  // 实际项目中这里应该上传到服务器并获取URL
  form.logo = URL.createObjectURL(file.raw); // 临时URL用于预览
  form.logoName = file.name;
};

// 分页方法
const handleCurrentChange = (val) => {
  currentPage.value = val;
  jumpPage.value = val;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  jumpPage.value = 1;
};

// 页码跳转
const handleJump = () => {
  if (!jumpPage.value) return;
  
  let page = Number(jumpPage.value);
  if (isNaN(page) || page < 1) {
    page = 1;
  } else if (page > totalPages.value) {
    page = totalPages.value;
  }
  
  currentPage.value = page;
  jumpPage.value = page;
};

// 返回操作
const handleReturn = () => {
  router.back();
};

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  if (!newVal.trim()) {
    handleSearch();
  }
});

// 监听总页数变化，修正页码
watch(totalPages, (newVal) => {
  if (currentPage.value > newVal && newVal > 0) {
    currentPage.value = newVal;
    jumpPage.value = newVal;
  }
});

// 初始化
onMounted(() => {
  initData();
  jumpPage.value = currentPage.value;
});
</script>

<style scoped>
.brand-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.return-btn {
  color: #666;
}

.action-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
  flex-wrap: wrap;
}

.brand-logo {
  width: 40px;
  height: 40px;
}

.pagination-area {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.total-info {
  color: #666;
}

.el-pagination {
  margin: 0;
}

.el-input {
  width: auto;
}

.empty-state {
  margin: 50px 0;
  text-align: center;
}

/* 按钮样式 */
.add-btn, .search-btn, .jump-btn, .inventory-btn {
  background-color: #00b4b4;
  border-color: #00b4b4;
}

.add-btn:hover, .search-btn:hover, .jump-btn:hover, .inventory-btn:hover {
  background-color: #009e9e;
  border-color: #009e9e;
}

.edit-btn {
  background-color: #f5a623;
  border-color: #f5a623;
  margin-right: 5px;
}

.edit-btn:hover {
  background-color: #d9901e;
  border-color: #d9901e;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #f54e4e;
  border-color: #f54e4e;
}

/* 品牌简介样式 */
.intro-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 上传信息样式 */
.upload-info {
  margin-top: 8px;
  color: #606266;
  font-size: 13px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .action-area {
    flex-wrap: wrap;
  }
  
  .pagination-area {
    justify-content: center;
  }
}
</style>